package com.cicadamob.contact.api.service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import android.util.Log;

public class ContactHttpClient {

	public static final String KEY = "B97FED4E9994E33353F2A65A063DFAA8A31428E11BD7AE59";

	public static final int TAKEDBFILEERROR = 808;
	private static int BUFFER_SIZE = 1024 * 16; // stream缓冲大小
	public static final int ARRAY_SIZE = 1024 * 8; // 每次读取缓冲大小

	// HTTP 响应代码
	public static final int CODE_OK = 200; // 创建成功
	public static final int CODE_CREATED = 201; // 创建成功
	public static final int CODE_BAD_REQUEST = 400; // 密码栏空
	public static final int CODE_REQUEST_ERROR = 404; // 资源请求错误
	public static final int CODE_CONFLICT = 409; // 已有用户，冲突
	public static final int CODE_UNAUTHORIZED = 401; // Unauthorized 客户试图未经授权访问
	public static final int CODE_SERVERERROR = 500; // 服务器异常
	public static final int CODE_NET_ERROR = 1000; // 网络连接错误
	public static final int CODE_TIMEOUT = 1011; // 网络连接超时
	public static final int SDCARD_NOTFOUND = 1404;// 当前手机不存在sdcard
	public static final int APP_NODATA = 800; // 没有应用
	public static final int APP_SERVERERROR = 801; // 服务端异常
	public static final int APP_NOPHONEDATA = 802; //
	public static final int TIMEOUT = 12; // 连接超时

	/**
	 * 下载经过GZIP压缩的流，然后解压成文件
	 * 
	 * @param baseUrl
	 *            请求路径
	 * @param params
	 *            参数
	 * @param dir
	 *            文件夹路径 文件保存的文件夹
	 * @param fileName
	 *            文件保存名称
	 * @return
	 */
	public static int downloadFile(String baseUrl, Map<String, String> params,
			String dir, String fileName) {
		int status = 0;
		InputStream is = null;
		HttpURLConnection conn = null;
		GZIPInputStream gis = null;
		FileOutputStream fos = null;

		try {
			URL url = null;
			url = new URL(baseUrl);

			String s = url.toString();
			Log.e("下载通讯录", s);

			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setReadTimeout(60 * 1000*5);
			// 设置请求参数
			for (Map.Entry<String, String> entry : params.entrySet()) {
				conn.setRequestProperty(entry.getKey(), entry.getValue());
				Log.e("下载通讯录", entry.getKey()+"="+entry.getValue());
			}

			conn.connect();
			url = null;
			// 判断文件目录是否存在
			File mFile = new File(dir);
			if (!mFile.exists()) {
				mFile.mkdirs();
			}
			// 判断文件是否存在
			mFile = new File(dir + "/" + fileName);
			if (!mFile.exists()) {
				mFile.createNewFile();
			}

			fos = new FileOutputStream(mFile);
			status = conn.getResponseCode();
			Log.e("downloadfile_code", "--------" + status);
			if (status == 200) {
				is = conn.getInputStream();
				// Log.e("requtestRequestPropert", is.available()+"");
				String encoding = conn.getHeaderField("Content-Encoding");
				boolean gzipped = encoding != null
						&& encoding.toLowerCase().contains("gzip");

				// if(gzipped){
				gis = new GZIPInputStream(is, BUFFER_SIZE);
				int i = -1;
				byte buf[] = new byte[ARRAY_SIZE];
				while ((i = gis.read(buf, 0, buf.length)) != -1) {
					fos.write(buf, 0, i);
				}
				fos.flush();
				// }

			}
		} catch (IOException e) {
			e.printStackTrace();
			e.printStackTrace();
			if (e instanceof SocketException
					|| (e.getMessage() != null && e.getMessage().contains(
							"connec"))) {
				status = CODE_NET_ERROR;
			} else if (e.getMessage() != null
					&& e.getMessage().contains("authentication")) {
				status = CODE_UNAUTHORIZED;
			} else {
				status = CODE_SERVERERROR;
			}
		} finally {
			try {
				if (is != null)
					is.close();
				if (gis != null)
					gis.close();
				if (fos != null)
					fos.close();
				if (conn != null)
					conn.disconnect();
				is = null;
				gis = null;
				fos = null;
				conn = null;
			} catch (Exception e) {
				e.printStackTrace();
				status = CODE_SERVERERROR;
			}
		}
		return status;
	}

	/**
	 * xml网络请求，返回经过没经过zip压缩
	 * @param xmlStr
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws SocketTimeoutException
	 */
	public static String postXML(String xmlStr, String url) throws IOException,
			SocketTimeoutException {
		URL tmpuri = new URL(url);
		if (tmpuri.getHost() == null)
			return null;
		if (tmpuri.getHost().compareTo("") == 0)
			return null;

		HttpURLConnection con = (HttpURLConnection) tmpuri.openConnection();
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		con.setRequestMethod("POST");
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty(
				"User-Agent",
				"Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");

		// 链接超时
		con.setConnectTimeout(5000);
		// con.connect();// 链接
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		DataOutputStream ds = new DataOutputStream(con.getOutputStream());
		byte[] xmlbytes = xmlStr.getBytes();
		ds.write(xmlbytes);

		Log.e("tag", "请求url = " + url);
		Log.i("tag", "传到服务器的xml = " + xmlStr);
		// writeLogUtil.WriteLog(Group_HTTP_Log, "grouphttp",
		// "请求url="+url+"\n"+"内容："+"\n"+xmlStr);
		// ds.writeBytes(xmlStr);
		ds.flush();
		ds.close();
		int code = con.getResponseCode();
		if (code == 200) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			Log.i("tag", "服务器返回的xml = " + buffer.toString());
			// writeLogUtil.WriteLog(Group_HTTP_Log, "grouphttp",
			// "响应url="+url+"\n"+"内容："+"\n"+buffer.toString());
			return buffer.toString();
		}

		return null;
	}
	
	
	
	/**xml网络请求，返回经过经过zip压缩
	 * @param xmlStr
	 * @param url
	 * @return
	 * @throws IOException
	 * @throws SocketTimeoutException
	 */
	public static String postZipXML(String xmlStr, String url)
			throws IOException, SocketTimeoutException {
		// URL tmpuri = new
		// URL("http://10.244.8.106:8080/portal/api/getUserCard");
		URL tmpuri = new URL(url);
		if (tmpuri.getHost() == null)
			return null;
		if (tmpuri.getHost().compareTo("") == 0)
			return null;

		HttpURLConnection con = (HttpURLConnection) tmpuri.openConnection();
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		con.setRequestMethod("POST");
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty(
				"User-Agent",
				"Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
		// 链接超时
		con.setConnectTimeout(5000);

		// con.connect();// 链接
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		DataOutputStream ds = new DataOutputStream(con.getOutputStream());
		ds.write(xmlStr.getBytes());
		// ds.writeBytes(xmlStr);
		Log.e("tag", "请求url = " + url);
		Log.i("tag", "传到服务器的xml = " + xmlStr);
//		writeLogUtil.WriteLog(Group_HTTP_Log, "grouphttp", "请求url="+url+"\n"+"内容："+"\n"+xmlStr);
		ds.flush();
		ds.close();
		if (con.getResponseCode() == 200) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new GZIPInputStream(con.getInputStream(),BUFFER_SIZE)));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			Log.i("tag", "服务器返回的xml = " + buffer.toString());
//			writeLogUtil.WriteLog(Group_HTTP_Log, "grouphttp", "响应url="+url+"\n"+"内容："+"\n"+buffer.toString());
			return buffer.toString();
		}

		return null;
	}

}
